# -*- coding: utf-8 -*-
# @project: huawang-api20230914
# @file： ht_api.py
# @Time：2023/7/17 14:09
# @Author：liaogan
import json

import allure
import os, time
from common.commin.commin import read_ini
from common.request.request_api import YkRequestHandler
from common.yaml.read_yaml import get_excel_yaml, get_time
from config.conf import BASE_DIR, Test_data
from common.log.log import log

from data.randomly_generated_data import generate_random_intro

from po.public_methods import yk_ui_login_backstage, yk_ht_api_login

url_yk = read_ini(BASE_DIR + '/config_yk.ini')['host']['url']
test_url_yk = read_ini(BASE_DIR + '/config_yk.ini')['host']['test_url']

class YkHtApi:
    def __init__(self):
        self.url = url_yk
        self.test_url = test_url_yk
    @allure.step("管理台云客新增商品场景")
    def add_product(self,token,price=0.02, cost=0.02, ot_price=0.02, stock=99, mod=1, Pro=True):
        # """
        # 云客管理台新增商品
        #  price=149, 售价
        #  cost=75,  成本价
        #  ot_price=149,  原价
        #  stock=99,
        #  mod=1 普通商品
        #  mod=2 会员礼包
        #  mod=3 云客礼包
        # """
        if Pro:
            if mod == 1:  # 普通商品
                try:
                    data = get_excel_yaml(os.path.join(Test_data, 'yk_add_comm.yaml'), alldata=True)[0]['data']
                    strtime = get_time(Y=True)  # 随机时间
                    data['store_name'] = 'auto_test06商品' + strtime  # 替换商品名称
                    data['store_info'] = generate_random_intro()  # 商品随机简介生成
                    # data['description'] = generate_random_intro()  # 商品详情描述
                    data['attrs'][0]['price'] = price  # 商品价格
                    data['attrs'][0]['cost'] = cost  # 成本价格
                    data['attrs'][0]['ot_price'] = ot_price  # 原价
                    data['attrs'][0]['stock'] = stock  # 库存
                    path = get_excel_yaml(os.path.join(Test_data, 'yk_add_comm.yaml'), alldata=True)[0]['url']
                    log.info('管理台api接口云客新增商品')
                    req = YkRequestHandler(token, 'yk')
                    get_url = self.url + path
                    response = req.visit('post', get_url, json=data)
                    return response.text
                except Exception as e:
                    log.error(f'管理台api接口新增商品出现异常为：{e}')
                    raise e
            elif mod == 2:  # 会员礼包
                try:
                    data = get_excel_yaml(os.path.join(Test_data, 'yk_add_comm.yaml'), alldata=True)[1]['data']
                    strtime = get_time(Y=True)  # 随机时间
                    data['store_name'] = 'auto_test会员礼包' + strtime  # 替换商品名称
                    data['store_info'] = generate_random_intro()  # 商品随机简介生成
                    # data['description'] = generate_random_intro()  # 商品详情描述
                    data['attrs'][0]['price'] = price  # 商品价格
                    data['attrs'][0]['cost'] = cost  # 成本价格
                    data['attrs'][0]['ot_price'] = ot_price  # 原价
                    data['attrs'][0]['stock'] = stock  # 库存
                    path = get_excel_yaml(os.path.join(Test_data, 'yk_add_comm.yaml'), alldata=True)[1]['url']
                    log.info('管理台api接口云客新增商品')
                    req = YkRequestHandler(token, 'yk')
                    get_url = self.url + path
                    response = req.visit('post', get_url, json=data)
                    return response.text
                except Exception as e:
                    log.error(f'管理台api接口新增云客礼包商品出现异常为：{e}')
                    raise e

            elif mod == 3:  # 云客礼包
                try:
                    data = get_excel_yaml(os.path.join(Test_data, 'yk_add_comm.yaml'), alldata=True)[2]['data']
                    strtime = get_time(Y=True)  # 随机时间
                    data['store_name'] = 'auto_test云客礼包' + strtime  # 替换商品名称
                    data['store_info'] = generate_random_intro()  # 商品随机简介生成
                    # data['description'] = generate_random_intro()  # 商品详情描述
                    data['attrs'][0]['price'] = price  # 商品价格
                    data['attrs'][0]['cost'] = cost  # 成本价格
                    data['attrs'][0]['ot_price'] = ot_price  # 原价
                    data['attrs'][0]['stock'] = stock  # 库存
                    path = get_excel_yaml(os.path.join(Test_data, 'yk_add_comm.yaml'), alldata=True)[2]['url']
                    log.info('管理台api接口云客新增商品')
                    req = YkRequestHandler(token, 'yk')
                    get_url = self.url + path
                    response = req.visit('post', get_url, json=data)
                    return response.text
                except Exception as e:
                    log.error(f'管理台api接口新增商品出现异常为：{e}')
                    raise e

        # 测试环境造数
        else:
            if mod == 1:  # 普通商品
                try:
                    data = get_excel_yaml(os.path.join(Test_data, 'yk_add_comm.yaml'), alldata=True)[0]['data']
                    strtime = get_time(Y=True)  # 随机时间
                    data['store_name'] = 'auto_test商品001_' + strtime  # 替换商品名称
                    data['store_info'] = generate_random_intro()  # 商品随机简介生成
                    # data['description'] = generate_random_intro()  # 商品详情描述
                    data['attrs'][0]['price'] = price  # 商品价格
                    data['attrs'][0]['cost'] = cost  # 成本价格
                    data['attrs'][0]['ot_price'] = ot_price  # 原价
                    data['attrs'][0]['stock'] = stock  # 库存
                    path = get_excel_yaml(os.path.join(Test_data, 'yk_add_comm.yaml'), alldata=True)[0]['url']
                    log.info('管理台api接口云客新增商品')
                    req = YkRequestHandler(token, 'yk')
                    get_url = self.test_url + path
                    response = req.visit('post', get_url, json=data)
                    return response.text
                except Exception as e:
                    log.error(f'管理台api接口新增商品出现异常为：{e}')
                    raise e
            elif mod == 2:  # 会员礼包
                try:
                    data = get_excel_yaml(os.path.join(Test_data, 'yk_add_comm.yaml'), alldata=True)[1]['data']
                    strtime = get_time(Y=True)  # 随机时间
                    data['store_name'] = 'auto_test会员礼包' + strtime  # 替换商品名称
                    data['store_info'] = generate_random_intro()  # 商品随机简介生成
                    # data['description'] = generate_random_intro()  # 商品详情描述
                    data['attrs'][0]['price'] = price  # 商品价格
                    data['attrs'][0]['cost'] = cost  # 成本价格
                    data['attrs'][0]['ot_price'] = ot_price  # 原价
                    data['attrs'][0]['stock'] = stock  # 库存
                    path = get_excel_yaml(os.path.join(Test_data, 'yk_add_comm.yaml'), alldata=True)[1]['url']
                    log.info('管理台api接口云客新增商品')
                    req = YkRequestHandler(token, 'yk')
                    get_url = self.test_url + path
                    response = req.visit('post', get_url, json=data)
                    return response.text
                except Exception as e:
                    log.error(f'管理台api接口新增云客礼包商品出现异常为：{e}')
                    raise e

            elif mod == 3:  # 云客礼包
                try:
                    data = get_excel_yaml(os.path.join(Test_data, 'yk_add_comm.yaml'), alldata=True)[2]['data']
                    strtime = get_time(Y=True)  # 随机时间
                    data['store_name'] = 'auto_test云客礼包' + strtime  # 替换商品名称
                    data['store_info'] = generate_random_intro()  # 商品随机简介生成
                    # data['description'] = generate_random_intro()  # 商品详情描述
                    data['attrs'][0]['price'] = price  # 商品价格
                    data['attrs'][0]['cost'] = cost  # 成本价格
                    data['attrs'][0]['ot_price'] = ot_price  # 原价
                    data['attrs'][0]['stock'] = stock  # 库存
                    path = get_excel_yaml(os.path.join(Test_data, 'yk_add_comm.yaml'), alldata=True)[2]['url']
                    log.info('管理台api接口云客新增商品')
                    req = YkRequestHandler(token, 'yk')
                    get_url = self.test_url + path
                    response = req.visit('post', get_url, json=data)
                    return response.text
                except Exception as e:
                    log.error(f'管理台api接口新增商品出现异常为：{e}')
                    raise e

    @allure.step("获取未上架商品列表")
    def list_product(self, token, id=False):
        """
        云客管理台获取未上架商品列表
        """
        try:
            path = 'webserver/api/yxStoreProduct?page=0&size=10&sort=id%2Cdesc&isShow=0&isDel=0&cateId='
            log.info('管理台api接口云客未上架商品列表')
            req = YkRequestHandler(token, 'yk')
            get_url = os.path.join(self.url, path)
            response = req.visit('get', get_url)
            shortname = response.json()['content'][0]["storeName"]
            ID = response.json()['content'][0]["id"]
            if id:
                if "自动化商品" in shortname:
                    log.info(f'要删除商品为:{shortname},ID为{ID}')
                    return response.json()['content'][0]['id']
            else:
                # return response.json()['content'][0]
                return response.text

        except Exception as e:
            log.error(f'管理台api接口花王云客未商品商品接口出现异常为：{e}')
            raise e

    @allure.step("删除未上架的商品")
    def Delete_product(self, token, deleteId, Pro_url=True):
        """
        云客管理台删除未上架的商品
        """
        try:
            path = 'webserver/api/yxStoreProduct/{}'.format(deleteId)
            log.info('管理台api接口删除未上架的商品')
            req = YkRequestHandler(token, 'yk')
            if Pro_url:
                get_url = os.path.join(self.url, path)
            else:
                get_url = os.path.join(self.test_url, path)

            response = req.visit('delete', get_url)
            return response.text
        except Exception as e:
            log.error(f'管理台api接口删除未上架的接口出现异常为：{e}')
            raise e

    @allure.step("获取待上架商品")
    def list_Unlisted_goods(self,token):
        """
        云客管理台删除未上架的商品
        """
        try:
            path = 'webserver/api/yxStoreProduct?page=0&size=10&sort=id%2Cdesc&isShow=0&isDel=0&cateId='
            log.info('管理台api接口获取待上架商品')
            req = YkRequestHandler(token, 'yk')
            get_url = os.path.join(self.test_url, path)
            response = req.visit('get', get_url)
            return response.text
        except Exception as e:
            log.error(f'管理台api接口获取待上架商品的接口出现异常为：{e}')
            raise e

    @allure.step("上架商品操作")
    def up_goods(self,token, ID):
        """
        云客管理台上架商品操作
        """
        try:
            path = 'webserver/api/yxStoreProduct/onsale/{}'.format(ID)
            log.info('管理台api接口上架商品操作')
            req = YkRequestHandler(token, 'yk')
            get_url = os.path.join(self.test_url, path)
            data = {"status": 0}
            response = req.visit('post', get_url, json=data)
            return response.text
        except Exception as e:
            log.error(f'管理台api接口删除未上架的接口出现异常为：{e}')
            raise e


if __name__ == '__main__':
    test_flag = 2

    if test_flag == 1:
        drive = yk_ui_login_backstage()
        cooke = drive.get_cookies()[-1]['value']
        token = cooke.replace('%20', ' ')  # 获取到的token需要替换掉"%20"为空

        """生产环境获取token"""
        res = YkHtApi()
        print(res.add_product(token, mod=3, Pro=True))
        print(res.add_product(token, mod=2, Pro=True))
        print(res.add_product(token, mod=1, Pro=True))

        # # time.sleep(5)
        # print(res.list_product(token,id=False))
        # deleteId=res.list_product(token,Did=True)
        # print(res.Delete_product(token, deleteId))



    elif test_flag == 2:
        """test环境获取token"""
        token = yk_ht_api_login()
        res = YkHtApi()
        # print(res.add_product(token, mod=3, Pro=False))
        print(res.add_product(token, mod=2, Pro=False))
        # print(res.add_product(mod=1, Pro=False))
        time.sleep(1)
        for one in json.loads(res.list_Unlisted_goods())['content']:
            # print(one['id'],one['storeName'])
            if "auto_test" in one['storeName']:
                res.up_goods(one['id'])
                # res.Delete_product(token,one['id'],Pro_url=False)
